package org.sl.flvplayer.view {
	import org.sl.flvplayer.data.Config;
	import org.sl.flvplayer.data.VideoItem;

	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * Displays the video and the previewimage and removes the old sources when a new video has to be shown.
	 * 
	 * @package org.sl.flvplayer.view
	 * @author Dan
	 * @version
	 * @see org.sl.flvplayer.view.PlayerScreen
	 */ 
	public class PlayerDisplay extends Sprite {
		
		private var videoSrc : VideoItem;
		private var previewimageAvailable : Boolean = false;

		/**
		 * PlayerDisplay constructor 
		 */
		public function PlayerDisplay(videoItem : VideoItem) {
			super();
			videoSrc = videoItem;
		}

		/**
		 * Adds the video to the displaylist.
		 * 
		 * @param videoItem current videoItem
		 */
		public function addVideo(videoItem : VideoItem) : void {
			videoSrc = videoItem;
			addChild(videoSrc.video);
			addEventListener(Event.ENTER_FRAME, imagehandler);
		}

		/**
		 * Image handler.
		 * 
		 * @param p_event
		 */
		private function imagehandler(p_event : Event) : void {	
			addPreviewimage();
		}

		/**
		 * Adds a previewimage and resizes it. 
		 */
		private function addPreviewimage() : void {
			//  Due to timing problems the if condition has to be prompted serveral times
			if(videoSrc.isLoaded() && Config.getInstance().autoPlay == false && videoSrc.videoPreviewimage.image != null) {			
				removeEventListener(Event.ENTER_FRAME, imagehandler);
				previewimageAvailable = true;
				addChild(videoSrc.videoPreviewimage.image);
				if (Config.getInstance().scalePreviewImageToVideoSize) resizePreviewimage();				
			}
		}

		/**
		 * Removes the previous sources from the playerscreen.
		 */
		public function reset() : void {
			removeChild(videoSrc.video); 	          
			removePreviewImage();
		}

		/**
		 * Checks whether there is allready a previewimage shown and removes it.
		 */
		public function removePreviewImage() : void {
			if(previewimageAvailable) {
				removeChild(videoSrc.videoPreviewimage.image);
				previewimageAvailable = false;
			}
		}

		/**
		 * Fits the previewimage to the size of the video.
		 */
		public function resizePreviewimage() : void {
			videoSrc.videoPreviewimage.image.width = videoSrc.video.width;
			videoSrc.videoPreviewimage.image.height = videoSrc.video.height;
		}
	}
}
